//
//  HZHomeVM.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/20.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import SDWebImage

class HZHomeVM: NSObject {
    
    //            if let imgUrl = imgVM.cellModel?.pic_urls?.first?.thumbnail_pic where imgVM.cellModel?.pic_urls?.count == 1 {
    //
    //                if let img = imgVM.cellModel?.retweeted_status?.pic_urls?.first?.thumbnail_pic where imgVM.cellModel?.retweeted_status?.pic_urls?.count == 1 {
    //
    //
    //                }
    //
    //            }
    
    
    //主页数据的数组
    var arrM:[HZHomeCellVm]?
    
 
    
    // MARK: -  获取单张配图的原始尺寸
    private func giveOneImg(arr:[HZHomeCellVm],finished:(sucee:Bool,count:Int)->()){
        
        
        //定义队列组
        let group = dispatch_group_create()
        
        
        //遍历找到整个 cell 的模型视图
        for imgVM in arr {
            
            
            //如果只有一张配图
            if imgVM.cellModel?.pic_urls?.count == 1 || imgVM.cellModel?.retweeted_status?.pic_urls?.count == 1{
                
                
                // 有可能是原创也有可能是转载
                let  urlImg:String? = (imgVM.cellModel?.pic_urls?.first?.thumbnail_pic != nil) ? imgVM.cellModel?.pic_urls?.first?.thumbnail_pic : imgVM.cellModel?.retweeted_status?.pic_urls?.first?.thumbnail_pic
                
                
//                print(urlImg)
                
                let url = NSURL(string: urlImg!)
                
                //放一个鸡蛋
                dispatch_group_enter(group)
                
                //下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, error, _, _, _) -> Void in
                    
                    //                    print("下载完成")
                    
                    //设置单图的尺寸***
                    imgVM.giveOneSize()
                    
                    //拿出鸡蛋
                    dispatch_group_leave(group)
                    
                })
                
                
            }
            
            
            
            
        }
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            
            //全部下载完之后的回调
            finished(sucee: true, count: arr.count)
        })
        

        
        
    }
    
    
    // MARK: -  网络请求首页数据
    func  giveHomeDate(finished:(sucee:Bool,count:Int)->(),isPull:Bool){
        
        
        //获取最后一个 cell 的 id编号
        var cellId: Int64 = 0
        var newId: Int64 = 0
        
             //如果上拉加载了
        if isPull {
            
//            print(arrM?.last?.cellModel)
            
           cellId = arrM?.last?.cellModel?.id ?? 0
            
            
            //防止有一个重复的 cell
            if cellId != 0{
                cellId--
            }
            
        }else {
            
            newId = arrM?.first?.cellModel?.id ?? 0
        }
        
    
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let paras = ["access_token":(HZOAuthVM.sharedVM.model?.access_token ?? ""),"max_id":"\(cellId)","since_id":"\(newId)"]
  
        
        //get 请求首页数据
        HZNetTools.sharedTools.deliveryThing(requestMethod: .Get, urlString: urlString, parameter: paras) { (thing, error) -> () in
            
            if error != nil {
                print("获取首页数据错误")
                
                //失败的闭包回调
                finished(sucee: false, count: 0)
            }
            //            print(thing)
            
            guard let responstObject = thing as? [String:AnyObject] else {
                
                print("获取的不是字典类型的数据")
                
                //失败的闭包回调
                finished(sucee: false, count: 0)
                return
            }
            
            guard let responstArr = responstObject["statuses"] as? [[String:AnyObject]] else{
                
                //失败的闭包回调
                finished(sucee: false, count: 0)
                return
            }
            
//                        print(responstArr)
            
            //定义一个可变的空数组来存储
            var arr = [HZHomeCellVm]()
            
            for value in responstArr{
                
                //字典转模型
                let model = HZHomeModel.init(dict: value)
                
                let cellVM = HZHomeCellVm()
                
                //存模型到 VM 里去
                cellVM.cellModel = model
                
                arr.append(cellVM)
            }
            
    
            
            //赋值给全局的
            
            //第一次没有数据就要先初始化一下
            if self.arrM == nil {
                self.arrM = [HZHomeCellVm]()
            }
            
            //如果是上拉刷新
            if isPull{
                
                
                print("上拉了\(arr.count)")
               
                self.arrM = self.arrM! + arr
            }else{
                
                   print("下拉了\(arr.count)")
                
                 self.arrM = arr + self.arrM!
            }
            
            
            
            //设置单图的情况下的尺寸
            self.giveOneImg(arr,finished: finished)

        }
        
    }

    
}
